package logic

import (
	"context"
	"fmt"
	"ns/app/applet/api/internal/code"
	"ns/pkg/consts"
	"ns/pkg/functions"

	"ns/app/applet/api/internal/svc"
	"ns/app/applet/api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type SendCodeLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

var (
	cacheMobileCodeCountPrefix = "cache:mobile:code:count:"
)

func NewSendCodeLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SendCodeLogic {
	return &SendCodeLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *SendCodeLogic) SendCode(req *types.SendCodeRequest) (resp *types.SendCodeResponse, err error) {
	// 如果5分钟内发的次数超过5次，就不再发送
	countKey := fmt.Sprintf("%s%s", cacheMobileCodeCountPrefix, req.Mobile)
	count, err := l.svcCtx.Redis.IncrbyCtx(l.ctx, countKey, 1)
	if err != nil {
		return nil, err
	}
	if count >= 5000 {
		return nil, code.ErrSendMessageLimit
	}
	// 设置过期时间, 之后count == 1 时设置
	if count == 1 {
		err = l.svcCtx.Redis.ExpireCtx(l.ctx, countKey, consts.CacheExpire*60)
		if err != nil {
			return nil, err
		}
	}
	// 生成消息code
	phoneCode, err := functions.GenMessageVerifyCode()
	if err != nil {
		return nil, err
	}

	// 设置到redis
	err = l.svcCtx.UserModel.SetMessageVerifyCode(l.ctx, req.Mobile, phoneCode)
	if err != nil {
		return nil, err
	}
	return &types.SendCodeResponse{
		Code: phoneCode,
	}, nil
}
